<?php

namespace app\index\controller;

use app\data\model\ActUserModel;
use app\index\service\EmailService;
use app\index\service\LoginUserService;
use think\facade\Validate;
use think\helper\Str;
use think\facade\Db;

class User extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->needLogin();
    }

    public function account()
    {
        if($this->request->isGet()){
            $this->fetch();
        }else{
            $data = $this->_vali([
                'email.require' => '邮箱不能为空！',
                'email.email' => '邮箱格式错误！',
                'code.require' => '邮箱验证码不能为空',
            ]);
            if(!$this->checkEmailCheckCode($data['email'],$data['code'])){
                $this->error('邮箱验证码错误！');
            }
            $user_id = LoginUserService::get('id');
            $email_exist = ActUserModel::where('email',$data['email'])->where('id','<>',$user_id)->value('id');
            if($email_exist){
                $this->error('此邮箱已使用！');
            }
            $user =ActUserModel::where('id',LoginUserService::get('id'))->findOrFail();
            $user->email = $data['email'];
            $user->save();

            LoginUserService::logout();
            $this->success('邮箱修改成功,请重新登录');
        }
    }
    //发送注册邮箱验证码
    public function sendEmailCheckCode()
    {
        $this->_vali(['email.require' => '缺少接收邮箱！', 'email.email' => '邮箱格式错误！']);
        $email = input('email');
        $code = $this->getEmailCheckCode($email);
        $res = EmailService::sendHtml($email, "变更邮箱验证码", "<p>您的邮箱绑定验证码为 <h2>{$code}</h2></p>");
        if ($res) {
            $this->success('邮箱验证码发送成功，请前往邮箱查收！');
        } else {
            $this->error('邮件擦送错误！');
        }
    }
    //获取邮件验证码
    private function getEmailCheckCode($email)
    {
        $code = Str::random(6);

        $save_key = 'account_email_code';
        $code_arr = session($save_key) ?: [];
        $code_arr[$email][] = $code;
        session($save_key, $code_arr);

        return $code;
    }

    //验证邮箱验证码
    private function checkEmailCheckCode($email, $code)
    {
        $save_key = 'account_email_code';
        $cache = session($save_key) ?: [];
        $code_arr = $cache[$email] ?? [];
        return in_array($code, $code_arr);
    }

    public function password()
    {
        if($this->request->isGet()){
            $this->fetch();
        }else{
            $data = $this->_vali([
                'password_old.require' => '旧密码不能为空！',
                'password_new.require' => '密码不能为空',
                'password_new.min:4' => '密码最少4个字符',
                'password_new.max:20' => '密码不能超过20个字符',
                'password_new.alphaNum' => '密码只能由字母、数字组成',
                'password_confirm.require' => '请确认密码必须！',
                'password_confirm.confirm:password_new' => '两次密码不一致！',
            ]);
            $user = ActUserModel::where('id',LoginUserService::get('id'))->findOrFail();
            $user->changePassword($data['password_old'],$data['password_new']);
            $this->success('密码变更成功！');

        }
    }

    private function getReginTree()
    {
        $region = Db::name('SystemRegion')->field('id,region_name as title,parent_id as pid')->select();
        //转化为树形结构
        return $this->array2Tree($region->toArray());

    }

    private function array2Tree($list, $pid = 0)
    {
        $tree = array();

        foreach ($list as $item) {
            if ($item['pid'] == $pid) {
                // 找到子节点
                $children = $this->array2Tree($list, $item['id']);
                // 如果有子节点，则添加到当前节点的children属性中
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                // 将当前节点添加到结果树中
                $tree[] = $item;
                // 从原始数组中移除已处理的节点，防止循环时重复处理
                unset($list[array_search($item, $list)]);
            }
        }

        return $tree;
    }

    /**
     * @name:职业发展
     * @author:Sam
     * @date:2024-04-15
     * @param:[string] param [desc]
    */
    public function user_files_dev(){
        $this->user = ActUserModel::where('id',LoginUserService::get('id'))->findOrFail();
        if(request()->isGet()){
            return $this->fetch();
        }else{
            $data = request()->post();
            $this->user->setAttrs($data);
            if($this->user->save()) return $this->success('操作成功');
            return $this->error('操作失败');
        }
       
    }

    public function info()
    {
        if($this->request->isGet()){
            $this->user = ActUserModel::where('id',LoginUserService::get('id'))->find(); 
            $this->regionList = $this->getReginTree();
            $this->fetch();
        }else{
            $data = input('post.');
            $user = ActUserModel::where('id',LoginUserService::get('id'))->find(); 
            // if($profile = input('profile')){
            //     $user->profile = $profile;
            // }
            
            if($phone = input('phone')){
                if(!Validate::is($phone,'mobile')){
                    $this->error('手机号格式错误！');
                }
                // $user->phone = $phone;
            }

            // if($name = input('name')){
            //     $user->setAttr('name',$name);
            // }
            unset($data['user-profile-input']);
         
            $user->setAttrs($data);
            $user->save();
            LoginUserService::login($user->toArray());
            $this->success('修改成功！');
        }
    }

}